package com.bbtShop.core.utils;

import com.bbtShop.core.model.UserMenuTree;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author : manke
 * @Description
 * @Date: 2020/11/1 12:36
 */

public class TreeUtil {

    /**
     * 创建树结构
     * @param regionTrees
     * @return
     */
    public static List<UserMenuTree> tree(List<UserMenuTree> regionTrees) {
        //返回的节点树
        List<UserMenuTree> rootNodes = new ArrayList<>();
        Iterator<UserMenuTree> it = regionTrees.iterator();
        while (it.hasNext()) {
            UserMenuTree next = it.next();
            //parent（上级Id）为0的是根节点
            if ("0".equals(next.getPid().toString())) {
                rootNodes.add(next);
                it.remove();
            }
        }
        //遍历，找到二级节点
        for (UserMenuTree regionTree : rootNodes) {
            List<UserMenuTree> child = getChild(regionTrees, regionTree.getId().toString());
            regionTree.setSubs(child);
        }
        return rootNodes;

    }

    /**
     * 查子节点
     *
     * @param regions
     * @param parentId
     * @return
     */
    private static List<UserMenuTree> getChild(List<UserMenuTree> regions, String parentId) {

        //子节点列表
        List<UserMenuTree> childList = new ArrayList<>();
        Iterator<UserMenuTree> it = regions.iterator();
        while (it.hasNext()) {
            UserMenuTree regionTree = it.next();
            if (parentId.equals(regionTree.getPid().toString())) {
                childList.add(regionTree);
                it.remove();
            }
        }

        //遍历 递归获取子节点的子节点
        for (UserMenuTree regionTree : childList) {
            List<UserMenuTree> child = getChild(regions, regionTree.getId().toString());
            regionTree.setSubs(child);
        }
        //递归出口  childList长度为0
        if (childList.size() == 0) {
            return new ArrayList<>();
        }
        return childList;
    }
}
